package com.s2sh.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

import com.s2sh.dao.PersonDao;
import com.s2sh.domain.Person;

public class PersonDaoHibernateImpl implements PersonDao {
	
	private SessionFactory sessionFactory ;

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public void savePerson(Person person) {
		Session session = sessionFactory.openSession() ;
		Transaction transaction = session.beginTransaction() ;
		session.save(person) ;
		transaction.commit() ;
		session.close() ;
	}

	@Override
	public void updatePerson(Person person) {
		Session session = sessionFactory.openSession() ;
		Transaction transaction = session.beginTransaction() ;
		session.update(person) ;
		transaction.commit() ;
		session.close() ;
 	}

	@Override
	public void deletePerson(Long id) {
		Session session = sessionFactory.openSession() ;
		Transaction transaction = session.beginTransaction() ;
		Person person = (Person)session.get(Person.class, id) ;
		session.delete(person) ;
		transaction.commit() ;
		session.close() ;
	}

	@Override
	public List<Person> findAll() {
		Session session = sessionFactory.openSession() ;
		List<Person> list = session.createQuery("from Person").list() ;
		session.close() ;
		return list;
	}

	@Override
	public Person findById(Long id) {
		Session session = sessionFactory.openSession() ;
		Person person = (Person)session.get(Person.class, id) ;
		session.close() ;
		return person;
	}

	@Override
	public void saveBatchPerson(Integer saveNum) {
		Session session = sessionFactory.openSession() ;
		Transaction transaction = session.beginTransaction() ;
		for (int i = 0; i < saveNum; i++) {
			Person person = new Person() ;
			person.setName("person-" + i) ;
			person.setDescription("batch-" + i) ;
			session.save(person) ;
			if(i % 50 == 0) {
				session.flush() ;
				session.clear() ;
			}
		}
		transaction.commit() ;
		session.close() ;
	}

	@Override
	public List<Person> findByPage(Integer firstResult, Integer maxResult) {
		Session session = sessionFactory.openSession() ;
		Query query = session.createQuery("from Person") ;
		query.setFirstResult(firstResult) ;
		query.setMaxResults(maxResult) ;
		List<Person> list = query.list() ;
		return list;
	}


}
